<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/2
 * Time: 11:00
 */

namespace Shop\Api;
use Shop\Model\OrdersModel;
use Shop\Model\OrderStatusHistoryModel;
use Admin\Model\MessageModel;
use Admin\Api\MessageApi;
use Shop\Api\OrdersApi;
use Shop\Api\AlipayNotifyApi;
use Shop\Api\WxpayNotifyApi;
use Shop\Api\OrderRefundApi;
use Shop\Api\OrderRefundMoneyApi;

/**
 * 订单状态变更接口
 * Class OrdersStatusApi
 * @package Shop\Api
 */
class OrderStatusApi{

    /**
     * 待支付－》已支付变更
     * 1. 检测支付状态
     */
    const PAY_ORDER = "Shop/OrderStatus/payOrder";

    /**
     * 待支付－》货到付款状态变更
     */
    const CASH_ON_DELIVERY = "Shop/OrderStatus/cashOndelivery";
    /**
     * 待发货－》已发货状态变更
     */
    const SHIPPED = "Shop/OrderStatus/shipped";
    /**
     * 待确认－》已确认状态变更
     */
    const CONFIRM_ORDER = "Shop/OrderStatus/confirmOrder";
    /**
     * 待确认－》取消状态变更
     */
    const BACK_ORDER = "Shop/OrderStatus/backOrder";
    /**
     * 确认收货
     * 已发货 -> 已收货 状态变更
     */
    const CONFIRM_RECEIVE = "Shop/OrderStatus/confirmReceive";
    /**
     * 已收货 －》退货 状态变更
     */
    const RETURNED = "Shop/OrderStatus/returned";
    /**
     * 订单评价－》完成 状态变更
     */
    const EVALUATION = "Shop/OrderStatus/evaluation";

    /**
     * 订单评价－》取消 状态变更
     */
    const CANCEL = "Shop/OrderStatus/cancelOrder";

    /**
     *
     */
    const CLOSE = "Shop/OrderStatus/closeOrder";
    /**
     * 正在退款－》已退款 状态变更
     */
    const REFUNDED = "Shop/OrderStatus/refunded";




    //****以下作为自动调用，请不要使用下面接口，除非你明确知道自己干嘛
    //****有疑问找@author hebiduhebi@126.COM
	
	/**
	 * 更新状态=》已取消
	 */
	const ORDER_STATUS_TO_CANCEL = "Shop/OrderStatus/orderStatusToCancel";
	
	/**
	 * 更新状态=》已收货
	 */
	const ORDER_STATUS_TO_RECIEVED = "Shop/OrderStatus/orderStatusToRecieved";
	
	/**
	 * 更新状态=》已完成
	 */
	const ORDER_STATUS_TO_COMPLETED = "Shop/OrderStatus/orderStatusToCompleted";

    /**
     * 更新状态=》已评价
     */
	const ORDER_STATUS_TO_AUTO_EVALUATION="Shop/OrderStatus/toAutoEvaluation";
	

    /**
     *
     */
    function __construct(){
        $this->model = new OrdersModel();
    }

    /**
     * 订单支付－货到付款操作
     * @param $ids  订单id数组
     * @return array
     */
//    public function cashOndelivery($ids,$isauto,$uid){
//        $orderHisModel = new OrderStatusHistoryModel();
//        //
//        foreach($ids as  $id){
//
//            $result = $this->model->where(array('id'=>$id))->find();
//
//            if($result == false){
//                return $this->returnErr($this->model->getDbError());
//            }
//
//            if(is_null($result)){
//                return $this->returnErr("订单ID错误!");
//            }
//
//            if($result['pay_status'] !=  OrdersModel::ORDER_TOBE_PAID){
//                return $this->returnErr("当前订单状态无法变更！");
//            }
//			//dump($result['orderid']);
//            $entity = array(
//                'reason'=>"用户选择货到付款支付!",
//                'order_code'=>$result['order_code'],
//                'operator'=>$uid,
//                'status_type'=>'PAY',
//                'cur_status'=>$result['pay_status'],
//                'isauto'=>0,
//                'next_status'=> OrdersModel::ORDER_CASH_ON_DELIVERY,
//            );
//
//            $this->model->startTrans();
//            $flag = true;
//            $return = "";
//
//            //设置订单状态为货到付款
//            $result = $this->model->where(array('id'=>$id))->save(array('pay_status'=> OrdersModel::ORDER_CASH_ON_DELIVERY));
//            if($result === false){
//                $flag = false;
//                $return = $this->model->getDbError();
//            }
//            if($result == 0){
//                $flag = false;
//                $return = "订单ID有问题!";
//            }
//
//            if($orderHisModel->create($entity,1)){
//                $result = $orderHisModel->add();
//                if($result === false){
//                    $flag = false;
//                    $return = $orderHisModel->getDbError();
//                }
//            }else{
//                $flag = false;
//                $return = $orderHisModel->getError();
//            }
//            //单个
//        }
//
//        if($flag){
//            $this->model->commit();
//            return $this->returnSuc($return);
//        }else{
//            $this->model->rollback();
//            return $this->returnErr($return);
//        }
//
//    }

	/**
	 * 返回错误结构
	 * @return array('status'=>boolean,'info'=>Object)
	 */
	protected function returnErr($info) {
		return array('status' => false, 'info' => $info);
	}
	
	/**
	 * 返回成功结构
	 * @return array('status'=>boolean,'info'=>Object)
	 */
	protected function returnSuc($info) {
		return array('status' => true, 'info' => $info);
	}


    /**
     * 订单发货操作
     * @param $order_code
     * @param $uid
     * @return array
     * @internal param $id
     * @internal param $isauto
     */
    public function shipped($order_code,$uid){
        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        if($result['order_status'] != OrdersModel::ORDER_TOBE_SHIPPED){
            return $this->returnErr("当前订单状态无法变更！");
        }

        $entity = array(
            'reason'=>"订单发货操作!",
            'order_code'=>$result['order_code'],
            'operator'=>$uid,
            'status_type'=>'ORDER',
            'isauto'=>0,
            'cur_status'=>$result['order_status'],
            'next_status'=> OrdersModel::ORDER_SHIPPED,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('order_status'=> OrdersModel::ORDER_SHIPPED));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }
        if($result == 0){
            $flag = false;
            $return = "订单ID有问题!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }



        if($flag){
            $this->model->commit();
            return $this->returnSuc($return);
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }

    }

    /**
     * 订单关闭操作
     * @param $order_code
     * @param $isauto
     * @param $uid
     * @return array
     * @internal param $id
     */
    public function closeOrder($order_code,$isauto,$uid){
        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        $entity = array(
            'reason'      =>"订单已关闭!",
            'order_code'  =>$result['order_code'],
            'operator'    =>$uid,
            'status_type' =>'ORDER',
            'isauto'      =>$isauto,
            'cur_status'  =>$result['order_status'],
            'next_status' =>OrdersModel::ORDER_CANCEL,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('order_status'=>OrdersModel::ORDER_CANCEL));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }

        if($result == 0){
            $flag = false;
            $return = "订单ID有问题，因为订单未被更新!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }

        if($flag){
            $this->model->commit();
            // 推送订单消息
            $entity = array(
                'from_id' =>0,
                'title'   =>MessageModel::MESSAGE_ORDER,
                'content' =>'您的订单:'.$order_code.'已关闭',
                'summary' =>'订单关闭',
                'extra'   =>'', //消息记录中的
            );
            $after_open = array('type'=>'go_activity','param'=>MessageModel::MESSAGE_ORDER_ACTIVITY,'extra'=>array('order_code'=>$order_code)); //推送参数
            $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,array(MessageModel::MESSAGE_ORDER,$entity,$uid,false,$after_open));
            if(!$r['status']) return $this->apiReturnSuc($r['info']);
            return $this->returnSuc('订单关闭成功');
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }
    }

    /**
     * 订单确认
     * @param $order_code
     * @param $is_auto
     * @param $uid
     * @return array
     */
    public function confirmOrder($order_code,$is_auto,$uid){
        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        if($result['order_status'] != OrdersModel::ORDER_TOBE_CONFIRMED){
            return $this->returnErr("当前订单状态无法变更！");
        }

        $entity = array(
            'reason'=>"订单确认操作!",
            'order_code'=>$result['order_code'],
            'operator'=>$uid,
            'status_type'=>'ORDER',
            'isauto'=>0,
            'cur_status'=>$result['order_status'],
            'next_status'=> OrdersModel::ORDER_TOBE_SHIPPED,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('order_status'=> OrdersModel::ORDER_TOBE_SHIPPED));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }
        if($result == 0){
            $flag = false;
            $return = "订单ID有问题!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }



        if($flag){
        	//订单确认库存减少
            $this->model->commit();
            return $this->returnSuc($return);
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }

    }

    /**
     * 退回订单
     * @param $order_code
     * @param $reason
     * @param $isauto
     * @param $uid
     * @return array
     */
    public function backOrder($order_code,$reason,$isauto,$uid){

        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        if($result['order_status'] != OrdersModel::ORDER_TOBE_CONFIRMED){
            return $this->returnErr("当前订单状态无法变更！");
        }

        $entity = array(
            'reason'=>$reason,
            'order_code'=>$result['order_code'],
            'operator'=>$uid,
            'status_type'=>'ORDER',
            'isauto'=>0,
            'cur_status'=>$result['order_status'],
            'next_status'=> OrdersModel::ORDER_BACK,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('order_status'=>OrdersModel::ORDER_BACK));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }
        if($result == 0){
            $flag = false;
            $return = "订单ID有问题!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }



        if($flag){
            $this->model->commit();
            return $this->returnSuc($return);
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }


    }

    /**
     * 确认收货操作
     * @param $order_code
     * @param $isauto
     * @param $uid
     * @return array
     */
    public function confirmReceive($order_code,$isauto,$uid){
        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        if($result['order_status'] != OrdersModel::ORDER_SHIPPED){
            return $this->returnErr("当前订单状态出错!");
        }

        $entity = array(
            'reason'=>"确认收货操作!",
            'order_code'=>$result['order_code'],
            'operator'=>$uid,
            'isauto'=>0,
            'status_type'=>'ORDER',
            'cur_status'=>$result['order_status'],
            'next_status'=>OrdersModel::ORDER_RECEIPT_OF_GOODS,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('order_status'=>OrdersModel::ORDER_RECEIPT_OF_GOODS));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }
        if($result == 0){
            $flag = false;
            $return = "订单ID有问题!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }



        if($flag){
            $this->model->commit();
            return $this->returnSuc($return);
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }
    }

    /**
     * 退货操作
     * @param $order_code
     * @param $isauto
     * @param $uid
     * @return array
     * @internal param $id
     */
    public function returned($order_code,$isauto,$uid){

        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        /*if($result['order_status'] == OrdersModel::ORDER_RECEIPT_OF_GOODS ){
            return $this->returnErr("当前订单状态出错!");
        }*/

        $entity = array(
            'reason'=>"订单退货操作!",
            'order_code'=>$result['order_code'],
            'operator'=>$uid,
            'status_type'=>'ORDER',
            'isauto'=>$isauto,
            'cur_status'=>$result['order_status'],
            'next_status'=>OrdersModel::ORDER_RETURNED,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('order_status'=>OrdersModel::ORDER_RETURNED));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }

        if($result == 0){
            $flag = false;
            $return = "订单ID有问题!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }



        if($flag){
            $this->model->commit();
            return $this->returnSuc($return);
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }
    }

    /**
     * 退款  - 管道操作
     * @param  [type]  $order_code [description]
     * @param  [type]  $isauto     [description]
     * @param  integer $thid       [description]
     * @param  string  $note       [description]
     * @param  [type]  $money      [description]
     * @param  boolean $goodsOff   [description]
     * @return [type]              [description]
     */
    public function refunded($order_code,$isauto,$thid=0,$note='',$money){
        $money = (float)$money;
        if($money<=0) return $this->returnErr('需要退款金额');
        //检查订单
        $r = $this->model->where(array('order_code'=>$order_code))->find();
        if(false === $r) return $this->returnErr($this->model->getDbError());
        if(!$r)          return $this->returnErr('订单order_code错误');
        $uid          = $r['uid']; //消费者UID
        $pay_code     = $r['pay_code'];
        $pay_balance  = (float)$r['price'];
        $type         = $r['pay_type'];
        $order_status = $r['order_status'];
        if($r['cs_status'] != OrdersModel::CS_PENDING ){
            //订单售后状态为 待处理
            return $this->returnErr("订单售后非待处理!");
        }
        $this->model->startTrans();
        //修改订单支付状态 为已退款
        $r = $this->model->where(array('order_code'=>$order_code))->save(array('pay_status'=>OrdersModel::ORDER_REFUND));
        if($r === false){
            $this->model->rollback();
            return $this->returnErr($this->model->getDbError());
        }
        // if($r == 0){
        //     $this->model->rollback();
        //     return $this->returnErr('订单已退款!');
        // }

        //添加订单历史变动记录
        $entity = array(
            'reason'      =>"订单退款成功!",
            'order_code'  =>$order_code,
            'operator'    =>UID,
            'status_type' =>'PAY',
            'isauto'      =>$isauto,
            'cur_status'  =>$order_status,
            'next_status' =>OrdersModel::ORDER_REFUND,
        );
        $orderHisModel = new OrderStatusHistoryModel();
        if($orderHisModel->create($entity,1)){
            if($orderHisModel->add() === false){
                return $this->returnErr($orderHisModel->getDbError());
            }
        }else{
            return $this->returnErr($orderHisModel->getError());
        }

        //订单售后记录通过审核
        $entity = array(
            'valid_status' =>1,
            'reply_msg'    =>$note,
            'order_code'   =>$order_code,
        );
        $result = apiCall(OrderRefundApi::SAVE_BY_ID,array($thid,$entity));
        if(!$result['status']){
            $this->model->rollback();
            $this->returnErr('操作失败');
        }
;
        if($money>0){
        //需要退款
            //检查支付金额
            $batch_no = date('Ymd').$thid.time();
            //查找交易号
            $pay_thid = 0; //第三方支付金额
            if($pay_code && in_array($type,array(1,2))){
                if($type === 1){
                    //支付宝
                    $r = apiCall(AlipayNotifyApi::GET_INFO,array(array('out_trade_no'=>$pay_code)));
                    // $url = 'Api/AlipayRefund/submit';
                }elseif($type === 2){
                    //微信
                    // $url = 'Api/WxpayApp/refundSubmit';
                    $r = apiCall(WxpayNotifyApi::GET_INFO,array(array('out_trade_no'=>$pay_code)));
                }
                if(!$r['status'] ){
                    // $trade_no = $r['info']['trade_no'];
                    LogRecord('INFO:' . $r['info'], '[FILE] ' . __FILE__ . ' [LINE] ' . __LINE__);
                    $this->model->rollback();
                    $this->returnErr('第三方交易记录查询失败');
                }
                if(empty($r['info'])){
                    $this->model->rollback();
                    $this->returnErr('没有第三方交易记录');
                }
                $pay_thid = (float)$r['info']['total_fee'];
            }
            if($money>($pay_thid + $pay_balance)){
                $this->model->rollback();
                $this->returnErr('退款金额超过了订单实际支付金额！');
            }
        }

        $data = $trade_no.'^'.$money.'^'.'协商退款';
        $entity = array(
            'order_code'     => $order_code,
            'reason'         => $data,//Refund_info['reason'],
            'result'         => 0,
            'result_data'    => '',
            'data'           => $data,
            'money'          => $money,
            'currency'       => 'RMB',
            'refund_channel' => $type,
            'batch_no'       => $batch_no,
        );
        $r = apiCall(OrderRefundMoneyApi::ADD,array($entity));
        if(!$r['status']){
            $this->model->rollback();
            $this->returnErr($r['info']);
        }elseif($r['info']<=0){
            // dump($r);exit;
            $this->model->rollback();
            $this->returnErr('操作失败:ORDER_REFUND_MONEY:ADD');
        }
        //修改订单售后状态为已通过
        // $r = apiCall(OrderRefundApi::CHANGE_SERVICE_STATUS,array($order_code,OrdersModel::CS_PROCESSED));
        // if(!$r['status']){
        //     $this->model->rollback();
        //     $this->returnErr($r['info']);
        // }elseif($r['info']<=0){
        //     $this->model->rollback();
        //     $this->returnErr('操作失败:ORDER_REFUND:CHANGE_SERVICE_STATUS');
        // }
        //余额增加 + 余额变动记录
        $r = apiCall(WalletApi::PLUS,array($uid,$money,getDatatree('WALLET_AFTERSALE'),'订单'.$order_code.'售后退款'));
        if(!$r['status']){
            $this->model ->rollback();
            $this->returnErr($r['info']);
        }elseif($r['info']<=0){
            $this->model->rollback();
            $this->returnErr('操作失败:WALLET:PLUS');
        }
        $this->model->commit();
        // 推送订单消息
        $text = '您的订单('.$order_code.')获得'.$money.'元的退款,请查看余额';
        $entity = array(
          'from_id' =>0,
          'title'   =>MessageModel::MESSAGE_ORDER,
          'content' =>$text,
          'summary' =>'退款申请已通过',
          'extra'   =>'', //消息记录中的
        );
        $after_open = array('type'=>'go_activity','param'=>MessageModel::MESSAGE_ORDER_ACTIVITY,'extra'=>array('order_code'=>$order_code)); //推送参数
        $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,array(MessageModel::MESSAGE_ORDER,$entity,$uid,false,$after_open));
        if(!$r['status']) return $this->returnSuc($r['info']);
        else return $this->returnSuc('退款成功');
    }


    /**
     * 订单评价操作
     * @param $id
     * @param $isauto
     * @param $uid
     * @return array
     */
    public function evaluation($order_code,$isauto,$uid){
        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        if($result['order_status'] != OrdersModel::ORDER_RECEIPT_OF_GOODS ){
            return $this->returnErr("当前订单状态出错!");
        }

        $entity = array(
            'reason'=>"订单评价操作!",
            'order_code'=>$result['order_code'],
            'operator'=>$uid,
            'status_type'=>'COMMENT',
            'isauto'=>0,
            'cur_status'=>$result['order_status'],
            'next_status'=>OrdersModel::ORDER_COMPLETED,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('comment_status'=>OrdersModel::ORDER_HUMAN_EVALUATED,'order_status'=>OrdersModel::ORDER_COMPLETED));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }

        if($result == 0){
            $flag = false;
            $return = "订单ID有问题!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }



        if($flag){
            $this->model->commit();
            return $this->returnSuc($return);
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }
    }


    /**
     * 支付状态变更
     * 未支付-》已支付
     * @param $trade_no  交易号（本地商户）
     * @param $order_code 订单编号
     * @param $uid  用户ID
     * @param $pay_type
     * @return array|mixed
     */
    public function payOrder($trade_no,$order_code,$uid,$pay_type){
        if(empty($order_code)){
            return $this->returnErr("订单ID不能为空!");
        }

        $map=array(
            'order_code'=>$order_code,
        );

        $result = apiCall(OrdersApi::GET_INFO,array($map));

        if(!$result['status']){
            return $result;
        }
        if(is_null($result['info'])){
            LogRecord("订单ID非法",__FILE__.__LINE__,'INFO');
            return $this->returnErr("订单ID非法!");
        }
        //0. 检测订单状态，防止重复修改
        $order = $result['info'];
        // 只有订单的支付状态为 未支付时才能继续执行，否则返回
        if($order['pay_status'] != OrdersModel::ORDER_TOBE_PAID){
            return $this->returnErr("已处理!");
        }
        $orderHisModel = new OrderStatusHistoryModel();
        $this->model->startTrans();
        $flag = true;
        $return = "";

        $entity = array(
            'reason'=>"订单支付操作!",
            'order_code'=>$order_code,
            'operator'=>$uid,
            'status_type'=>'PAY',
            'isauto'=>0,
            'cur_status'=>$order['pay_status'],
            'next_status'=>OrdersModel::ORDER_PAID,
        );
        //1. 保存本地交易号，与修改订单状态
        $result = $this->model->where($map)->save(array('pay_type'=>$pay_type,'pay_code'=>$trade_no,'pay_status'=>OrdersModel::ORDER_PAID));

        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }

        if($result == 0){
            $flag = false;
            $return = "订单ID有问题!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }


        if($flag){
            $this->model->commit();
            return $this->returnSuc($return);
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }


    }


    /**
     * 订单取消操作
     * @param $order_code
     * @param $isauto
     * @param $uid
     * @return array
     * @internal param $id
     */
    public function cancelOrder($order_code,$isauto,$uid){
        $orderHisModel = new OrderStatusHistoryModel();
        $result = $this->model->where(array('order_code'=>$order_code))->find();

        if($result == false){
            return $this->returnErr($this->model->getDbError());
        }

        if(is_null($result)){
            return $this->returnErr("订单ID错误!");
        }

        if($result['pay_status'] != OrdersModel::ORDER_TOBE_PAID ){
            return $this->returnErr("已支付订单，无法取消!");
        }

        if($result['order_status'] != OrdersModel::ORDER_TOBE_CONFIRMED ){
            return $this->returnErr("当前订单状态出错!");
        }

        $entity = array(
            'reason'      =>"用户取消了订单!",
            'order_code'  =>$result['order_code'],
            'operator'    =>$uid,
            'status_type' =>'ORDER',
            'isauto'      =>$isauto,
            'cur_status'  =>$result['order_status'],
            'next_status' =>OrdersModel::ORDER_CANCEL,
        );

        $this->model->startTrans();
        $flag = true;
        $return = "";

        $result = $this->model->where(array('order_code'=>$order_code))->save(array('order_status'=>OrdersModel::ORDER_CANCEL));
        if($result === false){
            $flag = false;
            $return = $this->model->getDbError();
        }

        if($result == 0){
            $flag = false;
            $return = "订单ID有问题，因为订单未被更新!";
        }

        if($orderHisModel->create($entity,1)){
            $result = $orderHisModel->add();
            if($result === false){
                $flag = false;
                $return = $orderHisModel->getDbError();
            }
        }else{
            $flag = false;
            $return = $orderHisModel->getError();
        }



        if($flag){
            $this->model->commit();
            // 推送订单消息
            $entity = array(
                'from_id' =>0,
                'title'   =>MessageModel::MESSAGE_ORDER,
                'content' =>'您已成功关闭订单:'.$order_code,
                'summary' =>'订单关闭成功',
                'extra'   =>'', //消息记录中的
            );
            $after_open = array('type'=>'go_activity','param'=>MessageModel::MESSAGE_ORDER_ACTIVITY,'extra'=>array('order_code'=>$order_code)); //推送参数
            $r = apiCall(MessageApi::PUSH_MESSAGE_WITH_TYPE,array(MessageModel::MESSAGE_ORDER,$entity,$uid,false,$after_open));
            if(!$r['status']) return $this->apiReturnErr($r['info']);
            return $this->returnSuc('订单关闭成功');
        }else{
            $this->model->rollback();
            return $this->returnErr($return);
        }
    }


    /****************************以下自动调用内容*******************************/

	 /**
       * 设置订单状态
       * TODO：需要记录状态变更日志
       * @param $interval 判断的间隔时间 秒 为单位
       * @return array
       */
	public function orderStatusToCancel($interval){
		$map['updatetime'] = array('lt',time()-$interval);
		$map['order_status'] = OrdersModel::ORDER_TOBE_CONFIRMED;
		$map['pay_status'] = OrdersModel::ORDER_TOBE_PAID;
		$saveEntity = array('order_status'=>OrdersModel::ORDER_CANCEL);
		$result = $this->model->create($saveEntity,2);

		if($result === false){
			return $this->returnErr($this->model->getError());
		}

		$result = $this->model->where($map)->lock(true)->save();

		if($result === FALSE){
			$error = $this->model->getDbError();
			return $this->returnErr($error);
		}else{
			return $this->returnSuc($result);
		}
	}

      /**
       * 设置订单状态
       * TODO：需要记录状态变更日志
       * @param $interval 判断的间隔时间 秒 为单位
       * @return array
       */
	public function orderStatusToRecieved($interval){
		$map['updatetime'] = array('lt',time()-$interval);
		$map['order_status'] = OrdersModel::ORDER_SHIPPED;
		$saveEntity = array('order_status'=>OrdersModel::ORDER_RECEIPT_OF_GOODS);
		$result = $this->model->create($saveEntity,2);
		if($result === false){
			return $this->returnErr($this->model->getError());
		}
		$result = $this->model->where($map)->lock(true)->save();

		if($result === FALSE){
			$error = $this->model->getDbError();
			return $this->returnErr($error);
		}else{
			return $this->returnSuc($result);
		}
	}

      /**
       *
       * 设置订单状态
       * TODO：需要记录状态变更日志
       * @param $interval 判断的间隔时间 秒 为单位
       *
       * @return array
       */
	public function orderStatusToCompleted($interval){
		$map['updatetime'] = array('lt',time()-$interval);
		$map['order_status'] = OrdersModel::ORDER_RECEIPT_OF_GOODS;
		//$map['comment_status']=array('NEQ',OrdersModel::ORDER_TOBE_EVALUATE);//评价状态不为0
		$result=apiCall(OrdersApi::QUERY,array($map, $page = array('curpage'=>0,'size'=>50), $order = "updatetime desc"));
		foreach($result['info'] as $order){
			$codes[]=$order['order_code'];
		}

		$saveEntity = array('order_status'=>OrdersModel::ORDER_COMPLETED);
		$result = $this->model->create($saveEntity,2);
		if($result === false){
			return $this->returnErr($this->model->getError());
		}
		$result = $this->model->where($map)->lock(true)->save();
        if($result === FALSE){
			$error = $this->model->getDbError();
			return $this->returnErr($error);
		}else{
			return $this->returnSuc($result);
		}
	}
	
	/**
	 * 自动评价
	 */
	public function toAutoEvaluation($interval){
		$map['updatetime'] = array('lt',time()-$interval);
		$map['order_status'] = OrdersModel::ORDER_RECEIPT_OF_GOODS;
		$map['comment_status']=OrdersModel::ORDER_TOBE_EVALUATE;
		
		$saveEntity = array('comment_status'=>OrdersModel::ORDER_SYSTEM_EVALUATED);
		$result = $this->model->create($saveEntity,2);
		if($result === false){
			return $this->returnErr($this->model->getError());
		}
		$result = $this->model->where($map)->lock(true)->save();
		if($result === FALSE){
			$error = $this->model->getDbError();
			return $this->returnErr($error);
		}else{
			return $this->returnSuc($result);
		}
	}
	
	
	


}